<template>
  <div class="users-form">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑客户' : '添加客户' }}</h2>
    </div>

    <el-card class="form-card">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        style="max-width: 600px"
      >
        <el-form-item label="客户姓名" prop="username">
          <el-input
            v-model="form.username"
            placeholder="请输入客户姓名"
            clearable
          />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="form.phone"
            placeholder="请输入手机号"
            clearable
          />
        </el-form-item>

        <el-form-item label="固定电话" prop="tel">
          <el-input
            v-model="form.tel"
            placeholder="请输入固定电话"
            clearable
          />
        </el-form-item>

        <el-form-item label="电子邮箱" prop="email">
          <el-input
            v-model="form.email"
            placeholder="请输入电子邮箱"
            clearable
          />
        </el-form-item>

        <el-form-item label="地址" prop="address">
          <el-input
            v-model="form.address"
            placeholder="请输入地址"
            clearable
          />
        </el-form-item>

        <el-form-item label="客户偏好" prop="hobby">
          <el-input
            v-model="form.hobby"
            type="textarea"
            :rows="3"
            placeholder="请输入客户偏好"
            clearable
          />
        </el-form-item>

        <el-form-item label="备注" prop="userNotes">
          <el-input
            v-model="form.userNotes"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            {{ isEdit ? '更新' : '保存' }}
          </el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { usersApi } from '@/api'
import type { Users } from '@/types'

const router = useRouter()
const route = useRoute()

// 响应式数据
const loading = ref(false)
const formRef = ref<FormInstance>()

const form = reactive<Users>({
  userId: undefined,
  username: '',
  phone: '',
  tel: '',
  email: '',
  address: '',
  hobby: '',
  userNotes: ''
})

// 表单验证规则
const rules: FormRules = {
  username: [
    { required: true, message: '请输入客户姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '客户姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 计算属性
const isEdit = computed(() => !!route.params.id)

// 获取客户详情
const fetchUserDetail = async (userId: number) => {
  try {
    const response = await usersApi.getById(userId)
    if (response.code === 200) {
      Object.assign(form, response.data)
    } else {
      ElMessage.error(response.message || '获取客户信息失败')
    }
  } catch (error) {
    console.error('获取客户详情失败:', error)
    ElMessage.error('获取客户信息失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    let response
    if (isEdit.value) {
      response = await usersApi.update(form)
    } else {
      response = await usersApi.add(form)
    }
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
      router.push('/base/users')
    } else {
      ElMessage.error(response.message || (isEdit.value ? '更新失败' : '添加失败'))
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('操作失败')
  } finally {
    loading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  router.push('/base/users')
}

// 初始化
onMounted(() => {
  if (isEdit.value) {
    const userId = Number(route.params.id)
    if (userId) {
      fetchUserDetail(userId)
    }
  }
})
</script>

<style scoped>
.users-form {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.form-card {
  max-width: 800px;
  margin: 0 auto;
}
</style> 